/*
 * @Author      : ZhouQiJun
 * @Date        : 2025-08-07 00:22:54
 * @LastEditors : ZhouQiJun
 * @LastEditTime: 2025-08-07 00:51:33
 * @Description : 投影静态类
 */
import type { ProjCode } from '@ol/types'
import { isNil } from 'es-toolkit'
import proj4 from 'proj4'

import { Projection } from 'ol/proj'
import { addProjection } from 'ol/proj'
import { get } from 'ol/proj.js'
import { register } from 'ol/proj/proj4'

const defs: { [key in ProjCode]: string } = { 'EPSG:4490': '+proj=longlat +ellps=GRS80 +no_defs +type=crs' }

type ProjectionsT = {
  [key in ProjCode]: (code: ProjCode) => Projection
}

const projections: ProjectionsT = {
  'EPSG:4490': (code): Projection => {
    proj4.defs(code, defs[code])
    register(proj4)
    const projection = new Projection({
      code,
      units: 'degrees',
      axisOrientation: 'neu',
    })
    projection.setExtent([-180, -90, 180, 90])
    projection.setWorldExtent([-180, -90, 180, 90])
    addProjection(projection)
    return projection
  },
}

/**
 * 静态地图投影辅助类（仅适用于ol）。
 */
export default class Projections {
  /**
   * 获取地图投影，如果不存在则注册。
   *
   * #注意：4490投影目前还有问题，请勿使用！
   * @param code 投影代码
   */
  public static get(code?: ProjCode): Projection | undefined {
    // 如果投影为null，则使用默认投影（由ol决定）
    if (isNil(code)) return undefined

    let projection = get(code)
    if (isNil(projection)) {
      if (isNil(projections[code])) {
        throw new Error('Unknown EPSG code: ' + code)
      }
      projection = projections[code](code)
    }
    return projection
  }
}
